﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.ApplicationBlock;
using System.Configuration;

namespace SSOExample
{
    public partial class SignInWithYammer : System.Web.UI.Page
    {
        private string RequestToken
        {
            get { return (string)ViewState["YammerRequestToken"]; }
            set { ViewState["YammerRequestToken"] = value; }
        }

        private string AccessToken
        {
            get { return (string)Session["YammerAccessToken"]; }
            set { Session["YammerAccessToken"] = value; }
        }

        private InMemoryTokenManager TokenManager
        {
            get
            {
                var tokenManager = (InMemoryTokenManager)Application["YammerTokenManager"];
                if (tokenManager == null)
                {
                    string consumerKey = ConfigurationManager.AppSettings["yammerConsumerKey"];
                    string consumerSecret = ConfigurationManager.AppSettings["yammerConsumerSecret"];
                    if (!string.IsNullOrEmpty(consumerKey))
                    {
                        tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                        Application["YammerTokenManager"] = tokenManager;
                    }
                }

                return tokenManager;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.TokenManager != null)
            {
                var yammer = YammerConsumer.CreateConsumer(this.TokenManager);
                string requestToken;
                Uri popupWindowLocation = YammerConsumer.PrepareRequestAuthorization(yammer, out requestToken);
                this.RequestToken = requestToken;
                string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');";
                this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true);
            }
        }
    }
}
